package com.example.secondhandspringboot.interceptor;

import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class GetGoodsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            if (token!=null){
                Map<String, Object> claims = JwtUtil.parseToken(token);
                Long userId = Long.valueOf(claims.get("userId").toString());
                BaseContext.setCurrentId(userId);
            }
        } catch (Exception e) {
            response.setStatus(401);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BaseContext.removeCurrentId();
    }
}
